package com.damage.purchase_dept.service.impl;

import com.damage.common.config.PurchasePlanConfig;
import com.damage.common.dto.OrderSender;
import com.damage.common.entity.*;
import com.damage.common.exception.IncorrectStateException;
import com.damage.common.exception.ObsoleteException;
import com.damage.common.exception.RelateException;
import com.damage.common.service.IPublicService;
import com.damage.purchase_dept.mapper.IOrderDetailMapper;
import com.damage.purchase_dept.mapper.IOrderMapper;
import com.damage.purchase_dept.service.IOrderService;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private IOrderMapper orderMapper;

    @Autowired
    private IOrderDetailMapper orderDetailMapper;

    @Autowired
    private IPublicService publicService;

    @Override
    public List<Order> generateOrderByPurchasePlanId(Integer purchasePlanId)
            throws IncorrectStateException,ObsoleteException{
        PurchasePlan purchasePlan = publicService.findPurchasePlanById(purchasePlanId);
        if (purchasePlan.getState() != PurchasePlanConfig.AUDITED_PASS) {
            throw new IncorrectStateException("采购计划不是审核通过状态，不能生成订单！");
        }
        if (purchasePlan.getIsObsolete() == PurchasePlanConfig.OBSOLETE){
            throw new ObsoleteException("采购计划已经过时，不能生成订单！");
        }
        //生成的订单
        List<Order> orders = new ArrayList<>();

        //获得采购计划详情
        List<PurchasePlanDetail> purchasePlanDetails = publicService.findDetailByPurchasePlanId(purchasePlanId);

        //获得才采购计划详情中所包括的供应商
        Set<Integer> supplierIdSet = new HashSet<>();
        for (PurchasePlanDetail detail : purchasePlanDetails) {
            Integer supplierId = detail.getSupplyGood().getSupplier().getId();
            supplierIdSet.add(supplierId);
        }

        for (Integer supplierId : supplierIdSet) {
            //要发送给供应商的订单详情
            List<OrderDetail> orderDetails = new ArrayList<>();
            //获得供应商
            Supplier supplier = publicService.findSupplierById(supplierId);
            //创建订单对象并设置属性值
            Order order = new Order();
            order.setPurchasePlanId(purchasePlanId);
            order.setOrderReceiver(supplier.getName());
            Double totalPrice = 0d;
            for (PurchasePlanDetail detail : purchasePlanDetails) {
                //获得单个供应商的订单价格总和
                if (detail.getSupplyGood().getSupplier().getId() == supplierId) {
                    totalPrice += detail.getPrice();
                    OrderDetail orderDetail = new OrderDetail();
                    orderDetail.setCount(detail.getCount());
                    orderDetail.setPrice(detail.getPrice());
                    orderDetail.setSupplyGood(detail.getSupplyGood());
                    orderDetails.add(orderDetail);
                }
            }
            order.setTotalPrice(totalPrice);

            //插入订单对象到数据库
            orderMapper.insert(order);

            //
            orders.add(order);

            //插入订单详情对象到数据库
            for (OrderDetail orderDetail : orderDetails) {
                orderDetail.setOrderId(order.getId());
            }
            orderDetailMapper.insertBatch(orderDetails);
        }
        //将对应的采购计划设置为已生成订单状态
        orderMapper.purchasePlanGenerated(purchasePlanId);
        return orders;
    }

    @Override
    public Integer setProcessInstanceId(Integer orderId, String processInstanceId) {
        return orderMapper.setProcessInstanceId(orderId, processInstanceId);
    }

    @Override
    @Transactional(readOnly = true)
    public Order findById(Integer orderId) {
        return orderMapper.findById(orderId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Order> findByPurchasePlanId(Integer purchasePlanId) {
        return orderMapper.findOrderByPurchasePlanId(purchasePlanId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<OrderDetail> findDetailByOrderId(Integer orderId) {
        return orderDetailMapper.findDetailByOrderId(orderId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Order> findByState(Integer state) {
        return orderMapper.findOrderByState(state);
    }

    @Override
    public Integer deleteByPurchasePlanId(Integer purchasePlanId) {
        Integer deleteCount = 0;
        List<Order> orders = findByPurchasePlanId(purchasePlanId);
        for (Order order : orders) {
            //删除订单详情
            deleteCount += orderDetailMapper.deleteByOrderId(order.getId());
        }
        //删除订单
        deleteCount += orderMapper.deleteByPurchasePlanId(purchasePlanId);
        return deleteCount;
    }

    @Override
    public Integer sendOrder(Integer orderId, OrderSender orderSender) throws RelateException{
        Order order = orderMapper.findById(orderId);
        if (!Strings.isNullOrEmpty(order.getProcessInstanceId())){
            throw new RelateException("订单那和存在的流程想关联，不能发送订单！");
        }
        return orderMapper.sendOrder(orderId,orderSender);
    }

}
